<?php

namespace app\modules\backend\controllers;

use Yii;
use app\models\Croptype;
use app\models\searchs\CroptypeeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;

/**
 * CroptypeController implements the CRUD actions for Croptype model.
 */
class CroptypeController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Croptype models.
     * @return mixed
     */
    public function actionIndex($id=1)
    {
        //$searchModel = new CroptypeeSearch();
        //$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $query=Croptype::find();
        $dataProvider=new ActiveDataProvider(['query'=>$query,]);
        if($id==1) {
            $query->Where([
                'level'=>1,
            ]);}
        else{
            $query->Where([
                'pid'=>$id,
            ]);
        }
        return $this->render('index', [
            'dataProvider'=>$dataProvider,'id'=>$id,
        ]);
    }

    /**
     * Displays a single Croptype model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $query=Croptype::find();
        $dataProvider=new ActiveDataProvider(['query'=>$query,]);
            $query->Where([
                'pid'=>$id,
            ]);
        return $this->render('index', [
            'dataProvider'=>$dataProvider,'id'=>$id,
        ]);
    }

    /**
     * Creates a new Croptype model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($id=0)
    {
        $model = new Croptype();
        if($id!=0)
        {
            $model->pid=$id;
        }
        if ($model->load(Yii::$app->request->post()))
        {
             $parent=Croptype::findone($model->pid);
             $level=$parent->level;
             $model->level=$level+1;
            //计算子类数量，加一成为编号，有待改进
            $query=Croptype::find();
            $query->where(['pid'=>$model->pid])->andWhere(['level'=>$model->level]);
            $kids=$query->select('code')->orderBy('code')->column();
            $flag=false;
            $i=1;
            for(;$i<=sizeof($kids);$i+=1){
               if($i<10)
                   $i='0'.$i;
                if(($parent->code.$i)!=$kids[$i-1]){
                    $flag=true;
                    $model->code=$parent->code.$i;
                    break;
                }
            }
            if($flag==false){
                $i=sizeof($kids)+1;
                if($i<10)
                    $i='0'.$i;
                $model->code=$parent->code.$i;
            }
            $model->save();
             //return $this->render('error',['kids'=>$kids,'i'=>$i]);
              return $this->redirect(['index', 'id'=> $model->pid]);
        } else {
            return $this->render('create', [
                'model' => $model,'id'=>$id,
            ]);
        }
    }

    /**
     * Updates an existing Croptype model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Croptype model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $pid=Croptype::findOne($id)->pid;
        $this->findModel($id)->delete();

        return $this->redirect(['index','id'=>$pid]);
    }

    /**
     * Finds the Croptype model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Croptype the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Croptype::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
